package com.office.listen;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class SessionLister implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext application = se.getSession().getServletContext();//getServletContext全局作用域
        Object totalcount = application.getAttribute("totalcount");
        if (totalcount==null){
            totalcount=1;
            application.setAttribute("totalcount",totalcount);
        }else {
            Integer i = Integer.parseInt(totalcount.toString());
            i++;
            application.setAttribute("totalcount",totalcount);
        }
//        if (application)
        System.out.println("监听session被创建,有新的会话访问啦:"+se.getSession().getId());

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext application = se.getSession().getServletContext();
        Object totalcount = application.getAttribute("totalcount");
        int i = Integer.parseInt(totalcount.toString());
        i--;
        application.setAttribute("totalcount",i);
        System.out.println("监听session被销毁啦"+se.getSession().getId());
    }
}
